#include "../include/Grid.hpp"

Grid::Grid()
    :_cellSize(30)
    ,_numRow(20)
    ,_numCol(10)
{
    initialize();
}

void Grid::Draw()
{
    const std::vector<Color> CellColors(getCellColors());
    for(unsigned int row = 0; row < _numRow; ++row)
    {
        for(unsigned int col = 0; col < _numCol; ++col)
        {
            //注意，第一个参数是x坐标，第二个参数是y坐标
            //以左上角为原点，从左往右为x轴，从上到下是y轴
            //这里直接将col和row颠倒，前面就可以按照习惯
            //从上到下为横坐标x，从左到右是纵坐标y
            //Tetris初始化窗口时，宽度是500，高度是620
            //20 * 30 = 600,10 * 30 = 300，宽度剩一点放分数和下一个方块
            //加11的原因是左边和上边留11的黑框框
            DrawRectangle(col * _cellSize + 11,row * _cellSize + 11,_cellSize - 1,_cellSize - 1,CellColors[_grid[row][col]]);
        }
    }
}

void Grid::initialize()
{
    for(unsigned int row = 0; row < _numRow; ++row)
    {
        for(unsigned int col = 0; col < _numCol; ++col)
        {
            _grid[row][col] = 0;
        }
    }
}

unsigned int Grid::ClearAllRow()
{
    int ClearRowNum = 0;
    //循环终止条件为大于等于0，就不要用unsigned int类型了，因为大于等于0，减1后变成最大值，依然满足条件
    for(int row = _numRow - 1; row >= 0; --row)//从下往上清理
    {
        if(RowIsFull(row))//满了
        {
            ClearRow(row);
            ++ClearRowNum;
        }
        else if(ClearRowNum > 0)//中间有一行被清理掉
        {
            moveRowDown(row,ClearRowNum);//剩余的方块要往下掉ClearRowNum行
        }
    }

    return ClearRowNum;
}

bool Grid::IsOutRange(unsigned int row,unsigned int col)
{
    return !(row >= 0 && row < _numRow && col >= 0 && col < _numCol);
}

unsigned int& Grid::grid(int row,int col)
{
    return _grid[row][col];
}

bool Grid::PosIsEmpty(unsigned int row,unsigned int col)
{
    return _grid[row][col] == 0;
}

bool Grid::RowIsFull(unsigned int row)
{
    bool IsFull = true;
    for(unsigned int col = 0; col < _numCol; ++col)
    {
        if(_grid[row][col] == 0)
        {
            IsFull = false;
            break;
        }
    }

    return IsFull;
}

void Grid::ClearRow(unsigned int row)
{
    for(unsigned int col = 0; col < _numCol; ++col)
    {
        _grid[row][col] = 0;
    }
}

void Grid::moveRowDown(unsigned int row,unsigned int ClearRowNum)
{
    for(unsigned int col = 0; col < _numCol; ++col)
    {
        _grid[row + ClearRowNum][col] = _grid[row][col];
    }
}

